package com.hxs.hxsserver.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.alibaba.fastjson.JSON;
import com.hxs.hxsserver.config.redis.RedisService;
import com.hxs.hxsserver.config.redis.UserKey;
import com.hxs.hxsserver.domain.dto.JsonResult;
import com.hxs.hxsserver.domain.dto.ResponseCode;
import com.hxs.hxsserver.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

@Slf4j
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Resource
    RedisService redisService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取Http请求和响应对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取当前请求路径信息
        String requestURI = request.getRequestURI();
        log.info("获取请求信息：" + requestURI);
        //过滤路径，设置不过滤的请求
        String[] urls = {"/swagger-ui.html", "/common/**", "/swagger-ui/**",
                "/swagger-resources/**",
                "/webjars/**",
                "/doc.html",
                "/images/**",
                "/v2/api-docs",
                "/login/passwordLogin",
                "/login/getPicCode"
        };
        // 这里填写你允许进行跨域的主机ip（正式上线时可以动态配置具体允许的域名和IP）
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        // 允许的访问方法
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, PATCH, OPTIONS");
        // Access-Control-Max-Age 用于 CORS 相关配置的缓存
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, content-type,x-requested-with,Authorization,Token,Access-Token, x-ui-request,lang");

        boolean check = check(requestURI, urls);
        //白名单请求则放行
        if (check) {
            filterChain.doFilter(request, response);
            return;
        }
        // 从 http 请求头中取出 token
        String token = request.getHeader("Authorization");
        if (StringUtils.isBlank(token)) {
            response.setStatus(HttpStatus.OK.value());
            JsonResult jsonResult = JsonResult.builder().code(ResponseCode.TOKEN_INVALID.getCode()).msg(ResponseCode.TOKEN_INVALID.getDesc()).build();
            // 返回类型,json格式
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            OutputStream out = response.getOutputStream();
            out.write(JSON.toJSONString(jsonResult).getBytes(StandardCharsets.UTF_8));
            out.flush();
            return;
        } else {
            String cacheToken = redisService.get(UserKey.userToken, request.getHeader("Authorization"), String.class);
            if (StringUtils.isBlank(cacheToken)) {
                response.setStatus(HttpStatus.OK.value());
                JsonResult jsonResult = JsonResult.builder().code(ResponseCode.TOKEN_INVALID.getCode()).msg(ResponseCode.TOKEN_INVALID.getDesc()).build();
                // 返回类型,json格式
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                OutputStream out = response.getOutputStream();
                out.write(JSON.toJSONString(jsonResult).getBytes(StandardCharsets.UTF_8));
                out.flush();
                return;
            }else {
                try {
                    Claims claims = JwtTokenUtil.parseToken(cacheToken);
                    Integer userId = claims.get("userId", Integer.class);
                }catch (Exception e){
                    JsonResult jsonResult = JsonResult.builder().code(ResponseCode.TOKEN_INVALID.getCode()).msg(ResponseCode.TOKEN_INVALID.getDesc()).build();
                    // 返回类型,json格式
                    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                    OutputStream out = response.getOutputStream();
                    out.write(JSON.toJSONString(jsonResult).getBytes(StandardCharsets.UTF_8));
                    out.flush();
                    return;
                }
            }
        }
        filterChain.doFilter(request, response);
    }

    public boolean check(String requestURI, String[] urls) {
        for (int i = 0; i < urls.length; i++) {
            //match方法用于匹配路径，确定路径是否一致，相同返回true，不同返回false
            boolean match = PATH_MATCHER.match(urls[i], requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}

